<template>
  <div class="role-container">
    <div>
      <!-- 按钮 -->
      <el-button v-heima="'92期'" type="danger" @click="addRole"> 添加角色 </el-button>
    </div>
    <div class="rl-table">
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" prop="name" label="角色名称" width="180">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="currentItem.name" type="text" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="state" label="启用" width="180">
          <template slot-scope="{ row }">
            <el-switch v-if="row.isEdit" v-model="currentItem.state" :active-value="1" :inactive-value="0" />

            <span v-else>{{ row.state == 1 ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="description" label="角色描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="currentItem.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <div v-if="row.isEdit">
              <el-button :loading="updataLoading" type="primary" size="mini" @click="updateRole"> 确定 </el-button>
              <el-button size="mini" @click="row.isEdit = false">
                取消
              </el-button>
            </div>
            <div v-else>
              <el-button type="text" @click=" putPermission(row.id)"> 分配权限 </el-button>
              <el-button type="text" @click="openEdit(row)"> 编辑 </el-button>
              <el-popconfirm title="确定删除吗？" style="margin-left: 10px" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" type="text"> 删除 </el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="rl-pag">
      <!-- 分页 -->
      <el-pagination :page-sizes="[3, 4, 6, 10]" :page-size="pageParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="30%" @close="close('ruleForm')">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="ruleForm.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色介绍" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button :loading="addLoading" type="primary" @click="submitForm('ruleForm')">
            立即创建
          </el-button>
          <el-button @click="resetForm('ruleForm')"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <assignPermission v-if="showPermissionDialog" ref="assignPermission" v-model="showPermissionDialog" :currentId="currentId" :permIds="permIds" />
  </div>
</template>
<script>
import { getRolesRequest, addRolesRequest, delRolesRequest, updateRolesRequest, getRolesListRequest } from '@/api/role'
//转平铺的树形结构
import { transListToTreeData } from '@/utils'
import assignPermission from "./components/assignPermission.vue";
export default {
  name: '',
  components: {
    assignPermission
  },
  data () {
    return {
      tableData: [],
      total: 0,
      pageParams: {
        page: 1,
        pagesize: 3
      },
      dialogVisible: false,
      ruleForm: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
      addLoading: false,
      updataLoading: false,
      currentItem: {},
      showPermissionDialog: false,
      currentId: null,
      permIds: []
    }
  },
  computed: {
  },
  created () {
    this.getRoles()
  },
  methods: {
    async getRoles () {
      const res = await getRolesRequest(this.pageParams)
      console.log(res)
      this.tableData = res.data.rows
      this.total = res.data.total

      this.tableData.forEach(item => {
        this.$set(item, 'isEdit', false)
      })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.pageParams.pagesize = val
      this.getRoles()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.pageParams.page = val
      this.getRoles()
    },
    addRole () {
      this.dialogVisible = true
    },
    //添加功能
    submitForm (formName) {
      this.$refs.ruleFormRef.validate(async (valid) => {
        this.addLoading = true
        if (valid) {
          await addRolesRequest(this.ruleForm)
          this.addLoading = false
          this.resetForm()
          this.getRoles()
        } else {

          this.addLoading = false

        }
      });
    },
    resetForm (formName) {
      this.$refs.ruleFormRef.resetFields();
      this.dialogVisible = false
    },
    close (formName) {
      this.resetForm(formName)
    },
    //删除
    async confirmDel (id) {
      if (this.tableData.length === 1) {
        this.pageParams.page === 1 ? this.pageParams.page = 1 : this.pageParams.page--
      }
      await delRolesRequest(id)
      this.getRoles()
    },
    //编辑按钮,打开当前行的编辑状态的函数
    openEdit (row) {
      //一个小bug 在编辑当前行的时候 应该把其他的isEdit状态 改为false----排他思想
      this.tableData.forEach(item => {
        item.isEdit = false
      })
      row.isEdit = true
      //当前编辑的数据不能是原始数据row,应该在基于row创建一个新地址,
      //浅拷贝
      this.currentItem = { ...row }
    },
    //编辑请求确认按钮
    async updateRole () {
      try {
        this.updataLoading = true
        await updateRolesRequest(this.currentItem)
        //更新页面 顺便关闭
        this.getRoles()
        this.updataLoading = false
      } catch (_) {//如果一个变量定义不了就是用 _
        //下面这个一定要写,请求如果报错了,要处理这个loading

        this.updataLoading = false
      }
    },
    async putPermission (id) {

      // this.$refs.assignPermission.getRolesList(id)
      const res = await getRolesListRequest(id)
      console.log(res)
      this.showPermissionDialog = true
      this.currentId = id
      this.permIds = res.data.permIds
    }
  }
}
</script>
<style lang='scss'  scoped>
.role-container {
  padding: 20px;
  .rl-table {
    margin: 20px 0;
  }
  .rl-pag {
    text-align: right;
  }
}
</style>
